<!-- eslint-disable @typescript-eslint/no-shadow -->
<!-- eslint-disable default-case -->
<script setup lang="tsx">
import { ref, toRefs } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { useAppStore } from '@/store/modules/app';
import { fetchGetMenuList } from '@/service/api/system/menu';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useDict } from '@/utils/dict';
import MenuForm, { type OperateType } from './components/menu-form.vue';

const appStore = useAppStore();
const { sys_is_frame, sys_is_visible, sys_is_cache, sys_normal_disable } = toRefs<any>(
  useDict('sys_is_frame', 'sys_normal_disable', 'sys_is_visible', 'sys_is_cache')
);

const { bool: visible, setTrue: openModal } = useBoolean();

const wrapperRef = ref<HTMLElement | null>(null);

const { columns, columnChecks, data, loading, pagination, getData } = useTable({
  apiFn: fetchGetMenuList,
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    // {
    //   key: 'menuId',
    //   title: $t('page.manage.menu.id'),
    //   align: 'center'
    // },
    {
      key: 'menuName',
      title: $t('page.manage.menu.menuName'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'menuType',
      title: $t('page.manage.menu.menuType'),
      align: 'center',
      width: 80,
      render: row => {
        const tagMap: Record<Api.Common.MenuType, NaiveUI.ThemeColor> = {
          M: 'success',
          C: 'primary',
          F: 'default'
        };

        // const label = $t(menuTypeRecord[row.menuType]);
        let label = '';
        switch (row.menuType) {
          case 'M':
            label = '目录';
            break;
          case 'C':
            label = '菜单';
            break;
          case 'F':
            label = '按钮';
            break;
        }

        return <NTag type={tagMap[row.menuType]}>{label}</NTag>;
      }
    },
    {
      key: 'icon',
      title: $t('page.manage.menu.icon'),
      align: 'center',
      width: 60,
      render: row => {
        // const icon = row.iconType === '1' ? row.icon : undefined;

        // const localIcon = row.iconType === '2' ? row.icon : undefined;

        return (
          <div class="flex-center">
            <SvgIcon icon={`ep:${row?.icon}`} class="text-icon" />
            {/* <SvgIcon icon={icon} localIcon={localIcon} class="text-icon" /> */}
          </div>
        );
      }
    },
    {
      key: 'component',
      title: $t('page.manage.menu.routePath'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'perms',
      title: '权限标识',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: $t('page.manage.menu.menuStatus'),
      align: 'center',
      width: 80,
      render: row => {
        if (row.status === null) {
          return null;
        }
        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          0: 'primary',
          1: 'error'
        };
        let label = '';
        switch (row.status) {
          case '0':
            label = '正常';
            break;
          case '1':
            label = '停用';
            break;
        }
        // const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'visible',
      title: $t('page.manage.menu.hideInMenu'),
      align: 'center',
      width: 80,
      render: row => {
        const hide: CommonType.YesOrNo = row.hideInMenu ? '0' : '1';

        const tagMap: Record<CommonType.YesOrNo, NaiveUI.ThemeColor> = {
          '0': 'error',
          '1': 'default'
        };
        let label = '';
        // const label = $t(yesOrNoRecord[hide]);
        switch (row.visible) {
          case '1':
            label = '是';
            break;
          case '0':
            label = '否';
            break;
        }
        return <NTag type={tagMap[hide]}>{label}</NTag>;
      }
    },
    {
      key: 'orderNum',
      title: $t('page.manage.menu.order'),
      align: 'center',
      width: 60
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      fixed: 'right',
      render: row => (
        <div class="flex-center justify-end gap-8px">
          {row.menuType === '1' && (
            <NButton type="primary" ghost size="small">
              {$t('page.manage.menu.addChildMenu')}
            </NButton>
          )}
          <NButton type="primary" ghost size="small">
            {$t('common.edit')}
          </NButton>
          <NPopconfirm>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ],
  transformer: (res: any) => {
    const { data } = res;
    const recordsWithIndex = data?.data.map((item: any, index: number) => {
      return {
        ...item,
        index: (1 - 1) * data?.data.length + index + 1
      };
    });

    return {
      data: recordsWithIndex,
      pageNum: 0,
      pageSize: 10,
      total: data?.data.length
    };
  }
});

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const operateType = ref<OperateType>('add');

function handleAdd() {
  operateType.value = 'add';
  openModal();
}

async function handleBatchDelete() {
  // request
  // console.log(checkedRowKeys.value);

  onBatchDeleted();
}

/** the edit menu data or the parent menu data when adding a child menu */
const editingData: Ref<API.System.MenuVo | null> = ref(null);

const allPages = ref<string[]>([]);

// async function getAllPages() {
//   const { data: pages } = await fetchGetAllPages();
//   allPages.value = pages || [];
// }

// function init() {
//   getAllPages();
// }

// init
// init();
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.manage.menu.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.menuId"
        remote
        :pagination="pagination"
        class="sm:h-full"
      >
        <template #empty>
          <Empty />
        </template>
      </NDataTable>
      <!--
 <MenuOperateModal
        v-model:visible="visible"
        :operate-type="operateType"
        :row-data="editingData"
        :all-pages="allPages"
        @submitted="getData"
      />
-->
      <MenuForm
        v-model:visible="visible"
        :sys-is-frame="sys_is_frame"
        :sys-is-visible="sys_is_visible"
        :sys-is-cache="sys_is_cache"
        :sys-status="sys_normal_disable"
        :operate-type="operateType"
        :row-data="editingData"
        :all-pages="allPages"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
